package com.community.controller;

import com.community.model.User;
import com.community.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegistrationController extends HttpServlet {
    private final UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.getRequestDispatcher("registration.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取表单数据
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String role = req.getParameter("role");
            if (role == null || role.isEmpty()) {
                role = "USER"; // 默认角色为普通用户
            }

            // 创建用户对象
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setRole(role);

            // 注册用户（调用已有的registerUser方法）
            userService.registerUser(user);

            // 注册成功，重定向到登录页面
            req.setAttribute("message", "注册成功，请登录");
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        } catch (IllegalArgumentException e) {
            // 处理验证错误
            req.setAttribute("error", e.getMessage());
            req.getRequestDispatcher("registration.jsp").forward(req, resp);
        } catch (Exception e) {
            // 处理系统错误
            req.setAttribute("error", "注册失败，请稍后重试");
            req.getRequestDispatcher("registration.jsp").forward(req, resp);
        }
    }
}